package com.banmao.algorithm.No401To500.No530;

import java.util.ArrayDeque;

/**
 *  效率肯定很低，不用测
 */
public class Solution1 {

    public int getMinimumDifference(TreeNode root) {
        if(root == null) {
            return 0;
        }

        // 层序遍历
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        int minSub = Integer.MIN_VALUE;

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if(poll.left != null) {
                    queue.add(poll.left);
                    // 找当前节点左侧树的最右子节点
                    TreeNode rightLeaf = findDeepRightLeaf(poll.left);
                    if(poll.val - rightLeaf.val < minSub) {
                        minSub = poll.val - rightLeaf.val;
                    }
                }
                if(poll.right != null) {
                    queue.add(poll.right);
                    // 找当前节点右侧树的最左子节点
                    TreeNode leftLeaf = findDeepLeftLeaf(poll.right);
                    if(poll.val - leftLeaf.val < minSub) {
                        minSub = poll.val - leftLeaf.val;
                    }
                }
            }
        }
        return minSub;
    }

    private TreeNode findDeepLeftLeaf(TreeNode root) {
        if(root.left == null) {
            return root;
        }
        return findDeepRightLeaf(root.left);
    }

    private TreeNode findDeepRightLeaf(TreeNode root) {
        if(root.right == null) {
            return root;
        }
        return findDeepRightLeaf(root.right);
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
